package job.manager.db.dao;

import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import job.manager.db.ec.UsersEB;

/**
 *  DAO class is responsible for communcation with the
 *  database regarding users.
 */
public class UserDAO {

    private EntityManager em;

    public UserDAO() {
        
    }

    public UserDAO(EntityManager em) {
        this.em = em;
    }

    public UsersEB getUser(Integer pk){
        return em.find(UsersEB.class, pk);
    }

    public UsersEB getUser(String username, String password){
        Query q = em.createNamedQuery("UsersEB.findByUserAndPassword");
        q.setParameter("userName", username);
        q.setParameter("password", password);
        return (UsersEB) q.getSingleResult();
    }

    public int insert(UsersEB user){
        if(user != null){
            em.persist(user);
            em.flush();
            return 1;
        }
        return 0;
    }

    public int update(UsersEB user){
        if( user != null){
            UsersEB u = em.merge(user);
            em.flush();
            //em.refresh(u);
            return 1;
        }
        return 0;
    }


    public int delete(UsersEB user){
        if(user != null){
            UsersEB u = em.merge(user);
            em.remove(u);
            return 1;
        }
        return 0;
    }

    public int delete(Integer pk){
        if(pk != null){
            return this.delete(em.find(UsersEB.class, pk));
        }
        return 0;
    }

    public Collection<UsersEB> getAllUsers() {
        Query q = em.createNamedQuery("UsersEB.findAll");
        return q.getResultList();
    }

    public Collection<UsersEB> getAllAdministrators() {
        Query q = em.createNamedQuery("UsersEB.findByIsAdmin");
        q.setParameter("isAdmin", true);
        return q.getResultList();
    }

    public Collection<UsersEB> getAllNoneAdministrators() {
        Query q = em.createNamedQuery("UsersEB.findByIsAdmin");
        q.setParameter("isAdmin", false);
        return q.getResultList();
    }

    public UsersEB getUserByUsername(String userName) {
        Query q = em.createNamedQuery("UsersEB.findByUserName");
        q.setParameter("userName", userName);
        return (UsersEB) q.getSingleResult();
    }
}
